<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/12/8 17:17
 * Desc: 分时时段
 */
class Model_Ferry_Period_Time extends ORM
{

    protected $_table_name = 'ferry_period_time';

    /**
     * 保存时间
     * @param $dates
     * @return true
     */
    public static function save_date($dates)
    {
        $date_ids = [];
        foreach ($dates as $date) {
            $id  = $date['id'];
            $orm = '';
            if ($id) {
                $orm = ORM::factory('ferry_period_time', $id);
            }

            if (empty($orm->id)) {
                $orm          = ORM::factory('ferry_period_time');
                $orm->addtime = time();
            }

            $orm->start   = $date['min'];
            $orm->end     = $date['max'];
            $orm->modtime = time();
            $orm->save();

            if ($orm->saved()) {
                $orm->reload();
                $date_ids[] = $orm->id;
            }
        }

        // 查询要删除的时段
        $del_ids_build = DB::select('id')
            ->from('ferry_period_time');
        if (!empty($date_ids)) {
            $del_ids_build->where('id', 'not in', $date_ids);
        }
        $del_ids = $del_ids_build->execute()
            ->as_array('id', 'id');

        if (!empty($del_ids)) {
            // 删除不存在的时段
            DB::delete('ferry_period_time')->where('id', 'in', $del_ids)->execute();

            // 删除相关套餐
            Model_Ferry_Ticket_Sku::del_by_period_time($del_ids);

            // 删除和景点关联的分时时段
            Model_Ferry_Ticket_Period_Time::del_by_period_time($del_ids);
        }

        return true;
    }

    /**
     * 通过id获取名称
     * @param $period_time_id
     * @return string
     */
    public static function get_name_by_id($period_time_id)
    {
        $period_time = DB::select()
            ->from('ferry_period_time')
            ->where('id', '=', $period_time_id)
            ->execute()
            ->current();

        $str = '';
        if ($period_time) {
            $str = $period_time['start'] . '-' . $period_time['end'];
        }
        return $str;
    }
}